package com.hengxinguotong.zhihuichengjian.ui.statistics.attendance;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.ViewPagerAdapter;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.statistics.OnActivityInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.weekpicker.MonthPickerDialog;
import com.hengxinguotong.zhihuichengjian.weekpicker.WeekPickerDialog;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.Month;
import com.hengxinguotong.zhihuichengjian.weekpicker.entity.Week;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/3/28
 * <p>
 * 考勤报表
 */

public class AttendanceFormDataActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.back_tv)
    HXTextView backTv;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.week_form_data)
    RadioButton weekFormData;
    @BindView(R.id.month_form_data)
    RadioButton monthFormData;
    @BindView(R.id.date_rg)
    RadioGroup dateRg;
    @BindView(R.id.search_date_tv)
    HXTextView searchDateTv;
    @BindView(R.id.attendance_form_data_vp)
    ViewPager attendanceFormDataVp;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;

    private int screenWidth,//屏幕宽度
            currentPage;//选中页
    private List<String> titleList;
    private List<Fragment> fragmentList;
    private ViewPagerAdapter viewPagerAdapter;
    private String startTime,//开始时间
            endTime;//结束时间（月报表时，为空）
    private boolean selectWeek;
    private Week selectedWeek;
    private Month selectedMonth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance_form_data);
        ButterKnife.bind(this);
        initBottomLineWidth();
        initWeek();
        initView();
    }

    private void initWeek() {
        selectWeek = true;
        selectedWeek = new Week();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        selectedWeek.setWeekBegin(calendar.getTime());
        startTime = selectedWeek.getWeekBeginDate1();
        calendar.add(Calendar.DAY_OF_MONTH, 6);
        selectedWeek.setWeekEnd(calendar.getTime());
        endTime = selectedWeek.getWeekEndDate1();
        searchDateTv.setText(selectedWeek.getSelectWeekBeginAndEnd());
    }

    private void initMonth() {
        selectWeek = false;
        selectedMonth = new Month();
        Calendar calendar = Calendar.getInstance();
        selectedMonth.setYear(calendar.get(Calendar.YEAR));
        selectedMonth.setMonth(calendar.get(Calendar.MONTH) + 1);
        startTime = selectedMonth.getYearAndMonth1();
        endTime = "";
        searchDateTv.setText(selectedMonth.getYearAndMonth3());
    }

    private void initView() {
        titleTv.setText(R.string.attendance_form_data);
        dateRg.setOnCheckedChangeListener(this);

        titleList = new ArrayList<>();
        titleList.add("出勤率");
        titleList.add("公司考勤排名");
        titleList.add("班组考勤排名");
        titleList.add("工时统计");

        fragmentList = new ArrayList<>();
        AttendanceFormDataAttendanceRateFragment rateFragment = AttendanceFormDataAttendanceRateFragment.newInstance(startTime, endTime);
        fragmentList.add(rateFragment);
        AttendanceFormDataCompanyRankingFragment rankingFragment = AttendanceFormDataCompanyRankingFragment.newInstance(startTime, endTime);
        rankingFragment.setScreenWidth(screenWidth);
        fragmentList.add(rankingFragment);
        AttendanceFormDataTeamStatisticsFragment teamStatisticsFragment = AttendanceFormDataTeamStatisticsFragment.newInstance(startTime, endTime);
        fragmentList.add(teamStatisticsFragment);
        AttendanceFormDataWorkTimeStatisticsFragment workTimeStatisticsFragment = AttendanceFormDataWorkTimeStatisticsFragment.newInstance(startTime, endTime);
        fragmentList.add(workTimeStatisticsFragment);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragmentList);
        attendanceFormDataVp.setAdapter(viewPagerAdapter);
        attendanceFormDataVp.setOffscreenPageLimit(4);
        currentPage = 0;
        attendanceFormDataVp.setCurrentItem(currentPage);

        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titleList == null ? 0 : titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setText(titleList.get(index));
                simplePagerTitleView.setTextSize(14);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_666666));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_f288ae5));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        attendanceFormDataVp.setCurrentItem(index);
                        currentPage = index;
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(getResources().getColor(R.color.color_f288ae5));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerDrawable(new ColorDrawable() {
            @Override
            public int getIntrinsicWidth() {
                return Utils.dip2px(AttendanceFormDataActivity.this, 30);
            }
        });

        final FragmentContainerHelper fragmentContainerHelper = new FragmentContainerHelper(magicIndicator);
        fragmentContainerHelper.setInterpolator(new OvershootInterpolator(1.0f));
        fragmentContainerHelper.setDuration(300);
        attendanceFormDataVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                fragmentContainerHelper.handlePageSelected(position);
                currentPage = position;
            }
        });
    }

    //初始化底部导航线的长度
    private void initBottomLineWidth() {
        DisplayMetrics me = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(me);
        //得到屏幕宽度的像素点
        screenWidth = me.widthPixels;
        //得到底部导航线的布局参数类对象
//        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) bottomLine.getLayoutParams();
        //将宽度设置为屏幕宽度的1/4-100
//        lp.width = screenWidth / 4 - 100;
        //设置线条边距50
//        lp.leftMargin = 50;
        //将布局参数设置回slider
//        bottomLine.setLayoutParams(lp);
    }

    @OnClick({R.id.back_tv, R.id.search_date_tv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_tv:
                finish();
                break;
            case R.id.search_date_tv:
                AlertDialog dialog = null;
                if (selectWeek) {
                    dialog = new WeekPickerDialog(AttendanceFormDataActivity.this, new WeekPickerDialog.OnWeekSelectListener() {
                        @Override
                        public void onWeekSelect(Week week) {
                            if (week == null) {
                                searchDateTv.setText("请选择");
                            } else {
                                selectedWeek = week;
                                searchDateTv.setText(week.getSelectWeekBeginAndEnd());
                                startTime = week.getWeekBeginDate1();
                                endTime = week.getWeekEndDate1();
                                initData();
                            }
                        }
                    });
                } else {
                    dialog = new MonthPickerDialog(AttendanceFormDataActivity.this, new MonthPickerDialog.OnMonthSelectListener() {
                        @Override
                        public void onMonthSelect(Month month) {
                            if (month == null) {
                                searchDateTv.setText("请选择");
                            } else {
                                selectedMonth = month;
                                searchDateTv.setText(month.getYearAndMonth2());
                                startTime = month.getYearAndMonth1();
                                endTime = "";
                                initData();
                            }
                        }
                    });
                }
                dialog.getWindow().setGravity(Gravity.BOTTOM);
                dialog.show();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (group.getId()) {
            case R.id.date_rg:
                switch (checkedId) {
                    case R.id.week_form_data:
                        initWeek();
                        break;
                    case R.id.month_form_data:
                        initMonth();
                        break;
                }
                break;
        }
        initData();
    }

    private void initData() {
        Fragment fragment = fragmentList.get(currentPage);
        if (fragment instanceof OnActivityInteractionListener) {
            ((OnActivityInteractionListener) fragment).OnActivityInteraction(startTime, endTime);
        }
    }

}
